const { delDir, mkdirpSync } = require("./utils");
const fs = require("fs");
const { analyseObj, mergeObj } = require("./contentProcessing");
const llmFetch = require("./llmFetch");
/**
 * 转换器 中文提取 key 翻译为有意义驼峰
 * @param {*} context
 * @returns
 */
const translateLang = async (context) => {
  console.log(
    `==== [start] [task=${context.contextFiles.length}] translateLang fn `
  );
  delDir(context.translateDir);
  for (const [index, file] of context.contextFiles.entries()) {
    try {
      console.log(`==== [start] [task=${index + 1}] translateLang`);
      const translateFile = fs.readFileSync(file.i18nFilePath, "utf8");
      const translateStr = translateFile.replace("export default ", "");
      const translate = fs.readFileSync(context.tplTranslate, "utf8");
      const result = await Promise.all(
        analyseObj(translateStr).map(async (obj) => {
          const { data } = await llmFetch(
            context.key,
            translate.replace("{{REQUEST_STR}}", JSON.stringify(obj, null, 2))
          );
          const str = data.choices?.[0]?.message?.content
            .replace(/\n/g, "")
            .replace(/.*```json/, "")
            .replace(/```.*/, "");
          return JSON.parse(str);
        })
      );
      const jsonTemp = mergeObj(result);
      Object.keys(jsonTemp)
        .filter((key) => !["p", "c"].includes(key))
        .forEach((key) => {
          jsonTemp.p = {
            ...jsonTemp.p,
            ...jsonTemp[key],
          };
          delete jsonTemp[key];
        });
      const prettier = require("prettier");
      const formattedCode = await prettier.format(
        `export default ${JSON.stringify(jsonTemp, null, 2)}`,
        {
          parser: "babel",
          ...(context.prettier || {}),
        }
      );
      mkdirpSync(file.translateDir);
      fs.writeFileSync(file.translatePath, formattedCode, "utf8");
      file.translateStatus = true;
      console.log(`SUCCESS translateLang ======${file.fullPath}`);
    } catch (error) {
      file.translateStatus = false;
      console.error(`ERROR translateLang ======${file.fullPath}`);
      console.log(JSON.stringify(file));
      console.error(error);
    }
  }
};
module.exports = translateLang;
